/*


 */

package manualTest;

import jas.bank.Account;
import jas.bank.Bank;
import jas.bank.BankImpl;
import jas.http.client.HttpClientImpl;
import jas.rpc.client.Base64ClientSerializer;
import jas.rpc.server.Base64ServerSerializer;
import jas.rpc.server.ObjectIdBank;
import jas.rpc.server.ObjectIdBankImpl;
import jas.rpc.RemoteException;
import jas.rpc.client.RpcClient;
import jas.rpc.http.RpcHttpClientImpl;
import jas.rpc.http.RpcHttpClientFormatterImpl;
import jas.rpc.http.RpcHttpResponseFactory;
import jas.rpc.http.RpcHttpServerFormatterImpl;
import jas.rpc.server.RpcListenerImpl;
import jas.rpc.client.StubFactoryImpl;
import jas.http.server.HttpServer;
import jas.http.server.NullLogger;
import jas.http.server.StdHttpServerFactory;
import jas.rpc.http.RpcHttpClientFormatterImpl;


/**
 *
 *
 */
public class StressTest {
    
    public static void run(String host, int port) throws RemoteException {
        RpcClient client = new RpcHttpClientImpl(new HttpClientImpl(host, port), new RpcHttpClientFormatterImpl(new Base64ClientSerializer()), new StubFactoryImpl());
        
        Bank bank = client.getRemote(Bank.class, "bank"); // RMI: Naming.lookup
        
        
        System.out.println("Starting");
        long startTime = System.nanoTime();
        Account a = bank.getAccount("hest");
        for (int i=1; i<=1000; i++) {
            int h = i % 4;
            switch (h) {
                case 0: a.deposit(2.4); break;
                case 1: a.withdraw(1.2); break;
                case 2: a.getBalance(); break;
                case 3: a.getName(); break;
            }
        }
        long endTime = System.nanoTime();
        System.out.println("DONE");
        
        long deltaTime = endTime - startTime;
        System.out.println("Time spent = " + (deltaTime / 1000000) + " millis");
    }
    
    public static void main(String[] args) throws RemoteException {
        HttpServer server = null;
        try {
            ObjectIdBank ids = new ObjectIdBankImpl();
            ids.bind("bank", new BankImpl()); // RMI: Naming.bind
            
            server = new HttpServer(new StdHttpServerFactory(new NullLogger(), new RpcHttpResponseFactory(new RpcListenerImpl(), new RpcHttpServerFormatterImpl(new Base64ServerSerializer(), ids))));
            new Thread(server).start();
            
            run("localhost", 8080);
        } finally {
            if (server != null) {
                server.stop();
            }
        }
        
    }
    
}
